package com.yuexun.dhdoctor.module.departmentDocumentNew;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.commun.ui.Act_Choice_Member;
import com.yuexun.dhdoctor.module.departmentDocumentNew.adapter.FileAdapter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.adapter.FilesAdapter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.bean.DocDepartBean;
import com.yuexun.dhdoctor.module.departmentDocumentNew.bean.ShareDocBean;
import com.yuexun.dhdoctor.module.departmentDocumentNew.model.impl.ShareDocModel;
import com.yuexun.dhdoctor.module.departmentDocumentNew.model.impl.ShareMemberModel;
import com.yuexun.dhdoctor.module.departmentDocumentNew.model.impl.UserDepartDocTreeModel;
import com.yuexun.dhdoctor.module.departmentDocumentNew.presenter.impl.AddDownloadNumPresenter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.presenter.impl.SetShareMemberPresenter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.presenter.impl.ShareDocPresenter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.presenter.impl.UserDepartDocTreePresenter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.view.IAddDownloadNumView;
import com.yuexun.dhdoctor.module.departmentDocumentNew.view.ISetShareMemberView;
import com.yuexun.dhdoctor.module.departmentDocumentNew.view.IShareDocView;
import com.yuexun.dhdoctor.module.departmentDocumentNew.view.IUserDepartDocTreeView;
import com.yuexun.dhdoctor.util.FileUtils;
import com.yuexun.dhdoctor.util.ListChangeUtil;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;
import com.yuexun.dhdoctor.widget.HttpDownloader;
import com.yuexun.dhdoctor.widget.LoadingDialog;


import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/11/29 0029.
 */

public class Act_Doc_Department_New extends BaseKJActivity implements IUserDepartDocTreeView, IShareDocView
        , ISetShareMemberView {

    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.file_list)
    FixedSwipeListView fileList;
    @Bind(R.id.files_list)
    FixedSwipeListView filesList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.ll_select_person)
    LinearLayout llSelectPerson;

    List<String> childInfos = new ArrayList<>();
    List<String> docIds = new ArrayList<>();
    List<String> types = new ArrayList<>();
    List<String> names = new ArrayList<>();
    String childInfo, docId, type, name;

    private LoadingDialog loadingDialog;

    private UserDepartDocTreePresenter docDepartPresenter;
    private ShareDocPresenter shareDocPresenter;
    private AddDownloadNumPresenter addNumPresenter;
    private SetShareMemberPresenter setPresenter;

    //当前目录
    private List<DocDepartBean> docDepartBeans = new ArrayList<>();

    private List<ShareDocBean> docDatas = new ArrayList<>();

    private List<ShareDocBean> downDoc = new ArrayList<>();
    private int downPosition = 0;

    FilesAdapter adapter;
    FileAdapter fileAdapter;

    private ArrayList<People> usersBeans_origin = new ArrayList<>();

    @Override
    public void setRootView() {
        setContentView(R.layout.act_doc_department_new);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        llSelectPerson.setVisibility(View.GONE);
        loadingDialog = new LoadingDialog(aty);
        docDepartPresenter = new UserDepartDocTreePresenter(this, new UserDepartDocTreeModel());
        shareDocPresenter = new ShareDocPresenter(this, new ShareDocModel());
        setPresenter = new SetShareMemberPresenter(this, new ShareMemberModel());
        childInfo = getIntent().getExtras().getString("info");
        docId = getIntent().getExtras().getString("docId");
        type = getIntent().getExtras().getString("type");
        name = getIntent().getExtras().getString("name");
        setContent();

        docDepartBeans = JSON.parseArray(childInfo, DocDepartBean.class);

        if (docDepartBeans.size() > 0) {
            adapter = new FilesAdapter(fileList, docDepartBeans, R.layout.item_file);
            fileList.setAdapter(adapter);
            llSelectPerson.setVisibility(View.VISIBLE);
        }
        ApiGetDocDatas();

        filesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final String[] filenames = docDatas.get(position).getDocName().split("\\.");
                if (FileUtils.isFileExist(AppConfig.FILE_CONTENT + docDatas.get(position).getFileUUId() + "." + filenames[filenames.length - 1])) {
                    FileUtils fileUtils = new FileUtils(aty);
                    Intent intent = fileUtils.openFile(FileUtils.getSDPATH() + AppConfig.FILE_CONTENT
                            + docDatas.get(position).getFileUUId() + "." + filenames[filenames.length - 1]);
                    try {
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ViewInject.toast("当前文件未下载");
                }
            }
        });

        fileList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                childInfos.add(childInfo);
                docIds.add(docId);
                types.add(type);
                names.add(name);

                childInfo = docDepartBeans.get(position).getChildList();
                docId = docDepartBeans.get(position).getDepartDocId();
                type = docDepartBeans.get(position).getDocType() + "";
                name = docDepartBeans.get(position).getDocName();

                setContent();

                docDatas.clear();
                fileAdapter.notifyDataSetChanged();

                docDepartBeans.clear();
                adapter.notifyDataSetChanged();

                docDepartBeans = JSON.parseArray(childInfo, DocDepartBean.class);

                if (docDepartBeans.size() > 0) {
                    llSelectPerson.setVisibility(View.VISIBLE);
                    adapter = new FilesAdapter(fileList, docDepartBeans, R.layout.item_file);
                    fileList.setAdapter(adapter);
                } else {
                    llSelectPerson.setVisibility(View.GONE);
                    adapter = new FilesAdapter(fileList, docDepartBeans, R.layout.item_file);
                    fileList.setAdapter(adapter);
                }

                ApiGetDocDatas();

            }
        });
    }

    private void isBack() {
        childInfo = childInfos.get(childInfos.size() - 1);
        docId = docIds.get(docIds.size() - 1);
        type = types.get(types.size() - 1);
        name = names.get(names.size() - 1);

        childInfos.remove(childInfos.size() - 1);
        docIds.remove(docIds.size() - 1);
        types.remove(types.size() - 1);
        names.remove(names.size() - 1);

        setContent();

        docDatas.clear();
        fileAdapter.notifyDataSetChanged();

        docDepartBeans.clear();
        adapter.notifyDataSetChanged();

        docDepartBeans = JSON.parseArray(childInfo, DocDepartBean.class);


        if (docDepartBeans.size() > 0) {
            adapter = new FilesAdapter(fileList, docDepartBeans, R.layout.item_file);
            fileList.setAdapter(adapter);
        } else {
            adapter = new FilesAdapter(fileList, docDepartBeans, R.layout.item_file);
            fileList.setAdapter(adapter);
        }

        ApiGetDocDatas();
    }

    private void setContent() {
        title.setText(name);
    }


    //设置文档列表请求
    private void ApiGetDocDatas() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("departDocId", docId);
        params.put("docType", type);
        params.put("pageIndex", 1 + "");
        params.put("pageSize", 999999 + "");
//            params.put("inquireKey", key);
        shareDocPresenter.getShareDocDatas(params);
    }


    @OnClick({R.id.back, R.id.tv_select_person, R.id.tv_download})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                if (childInfos.size() > 0) {
                    isBack();
                } else {
                    finish();
                }
                break;
            case R.id.tv_select_person:
                usersBeans_origin.clear();
                Bundle bundle = new Bundle();
                Intent intent = new Intent(this, Act_Choice_Member.class);
                bundle.putSerializable("persons", usersBeans_origin);
                bundle.putString("title", "共享设置");
                bundle.putString("type", "多选");
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
                break;
            case R.id.tv_download:
                setDown();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 10000:
                usersBeans_origin = (ArrayList<People>) data.getExtras().getSerializable("persons");
                setUpdate();
                break;
            default:
                break;
        }
    }


    //设置下载
    public void setDown() {
        downDoc.clear();
        downPosition = 0;
        for (ShareDocBean beanDate : docDatas) {
            if (beanDate.isSelect()) {
                downDoc.add(beanDate);
            }
        }
        if (downDoc.size() > 0) {
            loadingDialog.show();
            downloadFile(downDoc.get(downPosition));
        } else {
            ViewInject.toast("请选择要下载的文件");
        }
    }

    @Override
    public void showShareDocDatas(BaseEntity<ShareDocBean> getShareDocDatas) {
        if ("200".equals(getShareDocDatas.getStatus())) {
            docDatas.clear();
            docDatas = getShareDocDatas.getDatas();
            if (docDatas.size() > 0) {
                llSelectPerson.setVisibility(View.VISIBLE);
            }
            fileAdapter = new FileAdapter(filesList, docDatas, R.layout.item_files, aty);
            filesList.setAdapter(fileAdapter);
        } else {
            ViewInject.toast(getShareDocDatas.getMessage());
        }

        emptyLayout.dismiss();
    }

    @Override
    public void showDepartTree(BaseEntity<DocDepartBean> getDepartTree) {

    }


    private void downloadFile(final ShareDocBean selectDoc) {
        final String[] filenames = selectDoc.getDocName().split("\\.");
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpDownloader httpDownLoader = new HttpDownloader(aty);
                Log.e("---------", AppConfig.WEB_FILE + selectDoc.getFileUUId());
                handler.sendEmptyMessage(0);
                int result = httpDownLoader.downfile(AppConfig.WEB_FILE + selectDoc.getFileUUId(), AppConfig.FILE_CONTENT,
                        selectDoc.getFileUUId() + "." + filenames[filenames.length - 1]);
                if (result == 0 || result == 1) {   //下载成功或已经存在
                    downPosition = downPosition + 1;
                    if (downPosition < downDoc.size()) {
                        downloadFile(downDoc.get(downPosition));
                    } else {
                        addDownloadNum();
                        handler.sendEmptyMessage(1);
                    }
                } else if (result == -1) {         //下载失败
                    handler.sendEmptyMessage(2);
                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
//                    ViewInject.toast("开始下载...");
                    break;
                case 1:
                    ViewInject.toast("下载完成");
                    loadingDialog.dismiss();
                    break;
                case 2:
                    ViewInject.toast("下载失败");
                    loadingDialog.dismiss();
                    break;
            }
        }
    };

    private void addDownloadNum() {
        addNumPresenter = new AddDownloadNumPresenter(new ShareDocModel(), new IAddDownloadNumView() {
            @Override
            public void addDocDownloadNum(BaseEntity<String> bean) {
                fileAdapter.notifyDataSetChanged();
            }
        });

        List<String> fileUuid = new ArrayList<>();
        List<String> docId = new ArrayList<>();
        String strFileUuid;
        String strDocId;

        for (ShareDocBean item : downDoc) {
            fileUuid.add(item.getFileUUId());
            docId.add(item.getDocId() + "");
        }
        strFileUuid = ListChangeUtil.listToString(fileUuid, ";");
        strDocId = ListChangeUtil.listToString(docId, ";");

        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("fileUUId", strFileUuid);
        params.put("docId", strDocId);
        addNumPresenter.addDocDownloadNum(params);
    }

    //确定提交
    private void setUpdate() {
        List<String> memberIdList = new ArrayList<>();
        List<String> memberNameList = new ArrayList<>();
        List<String> departDocId = new ArrayList<>();
        String strMemberId;
        String strMemberName;
        String strDepartDocId;
        loadingDialog.show();

        for (ShareDocBean item : docDatas) {
            departDocId.add("b_" + item.getDocId());
        }

        for (People item : usersBeans_origin) {
            memberIdList.add(item.getUserId());
            memberNameList.add(item.getUserName());
        }
        strMemberId = ListChangeUtil.listToString(memberIdList, ";");
        strMemberName = ListChangeUtil.listToString(memberNameList, ";");
        strDepartDocId = ListChangeUtil.listToString(departDocId, ";");

        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("memberId", strMemberId);
        params.put("memberName", strMemberName);
        params.put("departDocId", strDepartDocId);
        params.put("fileType", "1");
        setPresenter.setShareMember(params);
    }

    @Override
    public void setShareMember(BaseEntity<String> bean) {
        if ("200".equals(bean.getStatus())) {
            ViewInject.toast("分享成功");
        } else {
            ViewInject.toast("分享错误");
        }
        loadingDialog.dismiss();
    }


}
